package com.ljq.web.module.user;

import com.ljq.web.util.ResponseModal;
import com.ljq.web.util.RestTemplateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import java.util.List;

/**
 * Created by linjq on 17/5/31.
 */
@Service
public class UserService  {


    @Autowired
    private UserDao dao;

    @Autowired
    private TransactionTemplate transactionTemplate;

    @Transactional(propagation = Propagation.NEVER)
//    @Transactional
    public UserEntity save(UserEntity user) throws InterruptedException {

        final UserEntity finalUser = user;
//        dao.save(user);
//        //编程事务
        transactionTemplate.execute(new TransactionCallback<Object>() {
            @Override
            public Object doInTransaction(TransactionStatus transactionStatus) {
                //do sql
                dao.save(finalUser);
                return null;
            }
        });


        //远程调用
        ResponseModal result = RestTemplateUtil.post("http://localhost:8081/user/save", "{\"name\":\"小明\"}");


        //成功后调用编程事务
        if(result.getStatus()==200) {
            transactionTemplate.execute(new TransactionCallback<Object>() {
                @Override
                public Object doInTransaction(TransactionStatus transactionStatus) {
                    //do sql
                    dao.save(finalUser);
                    return null;
                }
            });
        }


        return user;
    }

    public UserEntity findOne(long id){
        return dao.findOne(id);
    }


    public List<UserEntity> findAll(){
        return dao.findAll();
    }

}
